<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="课程标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入课程标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['college:banner:add']"
        >新增
        </el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="bannerList">
      <el-table-column label="课程标题" align="center" prop="title"/>
      <el-table-column label="轮播图片" align="center" prop="image">
        <template slot-scope="scope">
          <div>
            <el-popover placement="right" title="" trigger="click">
              <img :src="scope.row.image" alt="">
              <img slot="reference" :src="scope.row.image" alt="" style="max-height: 30px;max-width: 30px">
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="指向地址" align="center" prop="url" :show-tooltip-when-overflow="true">
        <template slot-scope="scope">
          <el-link :href="scope.row.url" target="_blank" type="primary">{{scope.row.url}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="开始时间" align="center" prop="starttime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.starttime|dateFilter('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endtime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.endtime|dateFilter('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告备注" align="center" prop="remark" :show-tooltip-when-overflow="true"/>
      <el-table-column label="创建时间" align="center" prop="createtime" width="180"></el-table-column>
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['college:banner:edit']"
            v-if="scope.row.status!==0"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleChangeStatusBanner(scope.row,2)"
            v-hasPermi="['college:banner:changeStatus']"
            v-if="scope.row.status===1"
          >上线
          </el-button>
          <el-button
            size="mini"
            type="warning"
            @click="handleChangeStatusBanner(scope.row,0)"
            v-hasPermi="['college:banner:changeStatus']"
            v-if="scope.row.status===2"
          >下线
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['college:banner:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程banner对话框 -->
    <el-dialog v-if="open" :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="课程标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入课程标题"/>
        </el-form-item>
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="轮播图片" prop="image">
              <UploadImage ref="imageUpload" @change="imageChange" :path="form.image"></UploadImage>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="生成指向地址" v-if="!form.id">
              <UploadImage @change="addressChange" :path="path"></UploadImage>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="指向地址" prop="url" >
          <el-input v-model="form.url" placeholder="请输入指向地址"/>
        </el-form-item>

        <el-form-item label="有效期范围" prop="daterange">
          <el-date-picker
            v-model="form.daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="摘要"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="addLoading" @click.native.prevent="submitForm">
          <span v-if="!addLoading">提 交</span>
          <span v-else>提 交 中...</span>
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listBanner, delBanner, addBanner, updateBanner,changeStatusBanner} from "@/api/college/banner";
  import UploadImage from '@/components/UploadImage';
  import {getBannerAddress} from "@/api/common";

  export default {
    components: {
      UploadImage
    },
    data() {
      return {
        addLoading: false,
        path: undefined,
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 课程banner表格数据
        bannerList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态 0 已下线 1 待上线 2已上线字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          image: undefined,
          url: undefined,
          status: undefined,
          starttime: undefined,
          endtime: undefined,
        },
        // 表单参数
        form: {
          status: "1"
        },
        // 表单校验
        rules: {
          daterange: [
            {type: 'array', required: true, message: '请选择有效期范围', trigger: 'change'},
          ],
          title: [
            {required: true, message: "标题不能为空", trigger: "blur"}
          ], image: [
            {required: true, message: "轮播图片不能为空", trigger: "blur"}
          ], url: [
            {required: true, message: "轮播图片指向地址不能为空", trigger: "blur"}
          ]
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("yy_app_status").then(response => {
        this.statusOptions = response.data;
      });
    },
    methods: {
      /** 查询课程banner列表 */
      getList() {
        this.loading = true;
        listBanner(this.queryParams).then(response => {
          this.bannerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 状态 0 已下线 1 待上线 2已上线字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.addLoading = false;
        this.path = undefined;
        this.form = {
          id: undefined,
          title: undefined,
          image: undefined,
          url: undefined,
          status: "1",
          starttime: undefined,
          endtime: undefined,
          remark: undefined,
          createtime: undefined,
          updatetime: undefined,
          daterange: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.form = {
          id: row.id,
          title: row.title,
          status: row.status ,
          daterange: [row.starttime, row.endtime],
          image: row.image,
          url: row.url,
          remark: row.remark
        };
        this.title = "编辑";
        this.open = true;
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.starttime = this.form.daterange[0];
            this.form.endtime = this.form.daterange[1];
            if (this.form.id) {
              updateBanner(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addBanner(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm(`是否确认删除标题为[${row.title}]的数据项?`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delBanner(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      handleChangeStatusBanner(row,status){
        const id = row.id;
        this.$confirm(`是否确认更改标题为[${row.title}]的状态?`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        }).then(function () {
          return changeStatusBanner({id:id,status:status});
        }).then(() => {
          this.getList();
          this.msgSuccess("更改成功");
        }).catch(function () {
        });
      },
      imageChange(message) {
        this.$set(this.form, 'image', message);
        this.$refs.form.validateField('image');
      },
      addressChange(message) {
        if (message) {
          getBannerAddress({imgUrl: message}).then(res => {
            this.$set(this.form, 'url', res.msg);
          });
        }
      }
    }
  };
</script>
<style scoped>
  .mb8 {
    margin-bottom: 8px;
  }
</style>
